package com.alma.talk;

import java.util.Map;

import org.omg.CORBA.ORB;

import com.alma.MTalk.PeerOperations;


public class PeerImpl implements PeerOperations {

	private ORB orb;
	private String pseudo;
	private PeerListener peerListener;
	private Map<String,Talker> clients;
	private TalkImpl localTalk;

	
	public PeerImpl(ORB orb, TalkImpl localTalk, String pseudo, PeerListener peerListener) {
		super();
		this.orb = orb;
		this.pseudo = pseudo;
		this.peerListener = peerListener;
		this.localTalk = localTalk;
	}

	@Override
	public String getInformations() {
		return pseudo;
	}

	@Override
	public void requestTalk(short numConvSideA, String subject,String myInformations, String myTalkIor) {
		Talker talker = clients.get(myInformations);
		if(talker==null){
			talker = new Talker(orb, subject, numConvSideA, myTalkIor, myInformations);
			clients.put(myInformations,talker);
		}
		else{
			talker.setTalkIor(myTalkIor);
		}
		
		//On accepte ou on refuse la connection
		if(peerListener.onTalkRequest(this,subject, myInformations)){//Le talk a été accepté			
			//On accepte
			short convId = localTalk.accept(numConvSideA, myTalkIor);
			//On confirme en distant
			talker.getTalk().accept(numConvSideA,convId, localTalk.getIOR());
		}
		else{
			talker.getTalk().deny(numConvSideA);
		}
	}

	/**
	 * @return the pseudo
	 */
	public String getPseudo() {
		return pseudo;
	}

	/**
	 * @param pseudo the pseudo to set
	 */
	public void setPseudo(String pseudo) {
		this.pseudo = pseudo;
	}

	/**
	 * @return the peerListener
	 */
	public PeerListener getPeerListener() {
		return peerListener;
	}

	/**
	 * @param peerListener the peerListener to set
	 */
	public void setPeerListener(PeerListener peerListener) {
		this.peerListener = peerListener;
	}

	
}
